<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1>POST请求</h1>
  <form id="form">
    <input type="text" name="name">
    <input type="text" name="age">
    <input type="text" name="sex">
    <button id="btn">提交</button>
  </form>
  <script>
    const oForm = document.getElementById('form')
    const oName = document.querySelector('#form input[name=name]');
    const oAge = document.querySelector('#form input[name=age]');
    const oSex = document.querySelector('#form input[name=sex]');
    const oBtn = document.getElementById('btn')
    oForm.onsubmit = function(){
      //获取到value的值
      const namevalue = oName.value
      const agevalue = oAge.value
      const sexvalue = oSex.value
      //测试
      console.log(namevalue,agevalue,sexvalue);
      //实列化
      const xhr = new XMLHttpRequest()
      //打开路径
      xhr.open('post','/adduser?',true)
      //发送请求
      xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")
      xhr.send(JSON.stringify({
        name: `${namevalue}`,
        age: `${agevalue}`,
        sex: `${sexvalue}`
      }));
      //绑定事件
      xhr.onreadystatechange=function(){
        if(xhr.readyState === 4 &&(xhr.status >= 200 && xhr.status <= 299)){
          console.log(xhr.responseText);
        }
      }
      //阻止事件默认行为
      return false  
    }
  </script>
</body>

</html>